import Layer from '../../../core/Layer';
import Point from '../../../core/Point';
import MultiLine from '../../../base/MultiLine';
import Polygon from '../../../base/Polygon';

export default class extends Layer {
    constructor(canvas, style, data = []) {
        super(canvas, style);
        this.count = style.count || 24 * 60 * 60;
        this.baseLine = style.baseLine || 0;
        this.data = data;
        this.onMaked = style.onMaked;
        this.baseY = style.baseY || 0;
    }

    make() {
        this.childs.splice(0, this.childs.length);
        if (this.data.length === 0) {
            return;
        }
        let max = Number.MIN_VALUE, min = Number.MAX_VALUE, maxD = max;
        let maxIndex = -1, minIndex = -1;
        for (let i = 0; i < this.data.length; i++) {
            const diff = Math.abs(this.data[i].value - this.baseLine);
            if (diff > max) {
                max = diff;
            }
            if (maxD < this.data[i].value) {
                maxD = this.data[i].value;
                maxIndex = i;
            }
            if (min > this.data[i].value) {
                min = this.data[i].value;
                minIndex = i;
            }
        }
        const yStep = this.height / 2 / max;
        const xStep = this.width / this.count;
        const base = this.baseLine - max;
        let points = [];
        for (let i = 0; i < this.data.length; i++) {
            const point = new Point(
              this.position.x + i * xStep,
              this.position.y + (this.data[i].value - base) * yStep
            );
            points.push(point);
        }
        let multi = new MultiLine(this.canvas, {
            color: this.color,
        }, points);
        let polygon = new Polygon(this.canvas, {
            color: this.color,
            alpha: 0.2,
            type: Polygon.TYPE.FILL,
        }, [
            new Point(this.position.x, this.baseY),
            new Point(this.position.x, points[0].y),
            ...points,
            new Point(points[points.length - 1].x, this.baseY),
        ] );
        this.addChild(polygon, multi);
        this.onMaked && this.onMaked({
            xStep,
            yStep,
            baseLine: this.baseLine,
            pcg: max,
            maxIndex,
            minIndex,
            max: maxD,
            min,
        });
    }
}
